package com.eastedu.superise;

import com.baomidou.mybatisplus.annotation.IEnum;
import org.springframework.jdbc.core.DataClassRowMapper;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.lang.NonNull;

import java.beans.PropertyDescriptor;
import java.sql.ResultSet;
import java.sql.SQLException;


/**
 * The type Custom data class row mapper.
 *	使用JdbcTemplate查询数据时，枚举转换
 * @param <T> the type parameter
 * @author ZHISHUAI.ZHANG
 * @since 2024.07.25
 */
public class CustomDataClassRowMapper<T> extends DataClassRowMapper<T> {

	public CustomDataClassRowMapper(Class<T> mappedClass) {
		super(mappedClass);
	}

	@Override
	protected Object getColumnValue(@NonNull ResultSet rs, int index, PropertyDescriptor pd) throws SQLException {
		Class<?> propertyType = pd.getPropertyType();
		if (IEnum.class.isAssignableFrom(propertyType)) {
			Object value = JdbcUtils.getResultSetValue(rs, index, Integer.class);
			if (value != null) {
				for (Object enumConstant : propertyType.getEnumConstants()) {
					IEnum<?> enumValue = (IEnum<?>) enumConstant;
					if (enumValue.getValue().equals(value)) {
						return enumValue;
					}
				}
				throw new SQLException("Failed to convert column value to enum: No matching enum constant for value " + value);
			}
			return null;
		} else {
			return super.getColumnValue(rs, index, pd);
		}
	}
}
